01 Workflow Introduction

Revealing your data (nearly) effortlessly,
at every step in your workflow


Workflow from data to decision


If there's no visualization at any of these stages, you're flying blind.

But visualization is often skipped as too hard to construct, particularly for big data.

What if it were simple to visualize anything, anywhere?


Good news/
Bad news


Lots of choices!
Too hard to
try them all,
learn them all, or
get them to work together.


PyViz:



Seamless interoperability
for browser-based
viz tools

Supported by Anaconda, Inc.


PyViz Goals:

  • Full functionality in browsers (not desktop)
  • Full interactivity (inside and out of plots)
  • Focus on Python users, not web programmers
  • Start with data, not coding
  • Work with data of any size
  • Exploit general-purpose SciPy/PyData tools
  • Focus on 2D primarily, with some 3D
  • Avoid entangling your data, code, and viz:
    • Same viz/analysis code in Jupyter, Python, HPC, ...
    • Widgets/apps in Jupyter, standalone servers, web pages
    • Jupyter as a tool, not part of the results

Exploring Pandas Dataframes

If your data is in a Pandas dataframe, it's natural to explore it using the .plot() method (based on Matplotlib). Let's look at a dataset of the number of cases of measles and pertussis (per 100,000 people) over time in each state:

In [1]:
import pandas as pd

df = pd.read_csv('../data/diseases.csv.gz')
df.head()
Out[1]:
Year Week State measles pertussis
0 1928 1 Alabama 3.67 NaN
1 1928 2 Alabama 6.25 NaN
2 1928 3 Alabama 7.95 NaN
3 1928 4 Alabama 12.58 NaN
4 1928 5 Alabama 8.03 NaN

Just calling .plot() won't give anything meaningful, because it doesn't know what should be plotted against what:

In [2]:
%matplotlib inline

df.plot();

But with some Pandas operations we can pull out parts of the data that make sense to plot:

In [3]:
import numpy as np

by_year = df[["Year","measles"]].groupby("Year").aggregate(np.sum)
by_year.plot();

Here it is easy to see that the 1963 introduction of a measles vaccine brought the cases down to negligible levels.

Exploring Data with HVPlot and Bokeh

The above plots are just static images, but if you import the hvplot package, you can use the same plotting API to get fully interactive plots with hover, pan, and zoom in a web browser:

In [4]:
import hvplot.pandas

by_year.hvplot()
Out[4]:
In [5]:
# Only needed here because we use matplotlib much later on...
import holoviews as hv
hv.extension('bokeh', 'matplotlib', width="100")

Here the interactive features are provided by the Bokeh JavaScript-based plotting library. But what's actually returned by this call is something called a HoloViews object, here specifically a HoloViews Curve . HoloViews objects display as a Bokeh plot, but they are actually much richer objects that make it easy to capture your understanding as you explore the data:

In [6]:
import holoviews as hv
vline = hv.VLine(1963).options(color='black')

m = by_year.hvplot() * vline * \
    hv.Text(1963, 27000, " Vaccine introduced", halign='left')
m
Out[6]:

while still always being able to access the original data involved for further analysis:

In [7]:
print(m)
m.Curve.I.data.head()
:Overlay
   .Curve.I :Curve   [Year]   (measles)
   .VLine.I :VLine   [x,y]
   .Text.I  :Text   [x,y]
Out[7]:
Year measles
0 1928 16924.34
1 1929 12060.96
2 1930 14575.11
3 1931 15427.67
4 1932 14481.11

For other plotting libraries, a given visualization that you construct is a dead end -- if you want to change it in some way, you'll need to reconstruct it from scratch with different settings.

Because HoloViews objects preserve your original data, you can now do more with your data than you could before, including anything you could do with the raw data, plus overlaying (as above), laying out in subfigures, slicing, sampling, setting options, and many other operations.

For instance, with HoloViews it's simple to break down the data in different ways. You can inspect each state individually:

In [8]:
measles_agg = df.groupby(['Year', 'State'])['measles'].sum()
by_state = measles_agg.hvplot('Year', groupby='State', width=500, dynamic=False)

by_state * vline
Out[8]:

Or pull out a couple of those to put side by side:

In [9]:
by_state["Texas"].relabel('Texas') + by_state["New York"].relabel('New York')
Out[9]:

Or to compare four states over time by overlaying:

In [10]:
states = ['New York', 'New Jersey', 'California', 'Texas']
measles_agg.loc[1930:2005, states].hvplot(by='State') * vline
Out[10]:

Or by faceting:

In [11]:
measles_agg.loc[1930:2005, states].hvplot('Year', col='State', width=200, height=150, rot=90) * vline
Out[11]:

Or as a different type of plot, such as a bar chart:

In [12]:
measles_agg.loc[1980:1990, states].hvplot.bar('Year', by='State', rot=90)
Out[12]:

Or with additional information, such as error bars:

In [13]:
df_error = df.groupby('Year').agg({'measles': [np.mean, np.std]}).xs('measles', axis=1)
df_error.hvplot(y='mean') * hv.ErrorBars(df_error, 'Year').redim.range(mean=(0, None)) * vline
Out[13]:

If we really want to invest a lot of time in making a fancy plot, we can customize it to try to show all the yearly data about measles at once:

In [14]:
def nansum(a, **kwargs):
    return np.nan if np.isnan(a).all() else np.nansum(a, **kwargs)
In [15]:
heatmap = df.hvplot.heatmap('Year', 'State', 'measles', reduce_function=nansum,
    logz=True, height=500, width=900, xaxis=None, flip_yaxis=True)

aggregate = hv.Dataset(heatmap).aggregate('Year', np.mean, np.std)
agg = hv.ErrorBars(aggregate) * hv.Curve(aggregate).options(xrotation=90)
agg = agg.options(height=200, show_title=False)

marker = hv.Text(1963, 800, u'\u2193 Vaccine introduced', halign='left')
In [16]:
(heatmap + (agg * marker).options(width=900)).cols(1)
Out[16]:

If you prefer, you can choose Matplotlib to render your HoloViews plots, though you give up the interactive pan, zoom, and hover from Bokeh:

%%output backend='matplotlib' by_state hv.VLine(1963).options(color="black") \ hv.Text(1963, 1000, " Vaccine introduced", halign='left')

As you can see, these tools make it very quick to explore your data in a browser, and if you choose HoloViews+Bokeh plots, you can have full interactivity with very little code even for quite complex datasets.

Interactive statistical plots

For high-dimensional datasets with additional data variables, we can compose all the above faceting methods as needed.

For instance, let's look at the Iris dataset:

In [17]:
from bokeh.sampledata.iris import flowers as iris

iris.tail()
Out[17]:
sepal_length sepal_width petal_length petal_width species
145 6.7 3.0 5.2 2.3 virginica
146 6.3 2.5 5.0 1.9 virginica
147 6.5 3.0 5.2 2.0 virginica
148 6.2 3.4 5.4 2.3 virginica
149 5.9 3.0 5.1 1.8 virginica

We can now look at all these relationships at once, interactively:

In [18]:
hvplot.scatter_matrix(iris, c='species')
Out[18]:

Branching out: large data, geo data, custom controls

PyViz is a modular suite of tools, and when you need capabilities not handled by Bokeh and HoloViews (and optionally hvPlot) as above, you can bring those in:

  • GeoViews : Visualizable geographic HoloViews objects
  • Datashader : Rasterizing huge HoloViews objects to images quickly
  • Panel : Declarative parameters
  • Param : Making it simple to work with widgets inside and outside of a notebook context
  • Colorcet : perceptually uniform colormaps for big data

We'll look at a large(ish) dataset of 10 million taxi trips on a map, with the following caveat:

The following examples rely on dynamic updates from a live Python server, and will not update fully when viewed statically on a standard website.

In [19]:
import dask.dataframe as dd, geoviews as gv, cartopy.crs as crs
from colorcet import fire
from holoviews.operation.datashader import datashade
from geoviews.tile_sources import EsriImagery

topts = dict(width=700, height=600, bgcolor='black', xaxis=None, yaxis=None, show_grid=False)
tiles = EsriImagery.clone(crs=crs.GOOGLE_MERCATOR).options(**topts) 

dopts = dict(width=1000, height=600, x_sampling=0.5, y_sampling=0.5)
taxi  = dd.read_parquet('../data/nyc_taxi_wide.parq').persist()
pts   = hv.Points(taxi, ['pickup_x', 'pickup_y'])
trips = datashade(pts, cmap=fire, **dopts)

tiles * trips
Out[19]:

As you can see, you can specify geo plots easily with GeoViews, and if your HoloViews objects are too big to visualize in a browser directly, you can add datashade() to render them into images dynamically on zooming, etc.

You can also easily add widgets to control filtering, selection, and other options interactively, either here in the notebook, or in a standalone server by marking the servable objects with .servable() then running the .ipynb file through Bokeh Server or extracting the code to a separate .py file and doing the same thing:

In [20]:
import param, panel as pn
from colorcet import palette

class NYCTaxi(param.Parameterized):
    alpha = param.Magnitude(default=0.75, doc="Map tile opacity")
    cmap = param.ObjectSelector('fire', objects=['fire','bgy','bgyw','bmy','gray','kbc'])
    location = param.ObjectSelector(default='dropoff', objects=['dropoff', 'pickup'])

    def make_view(self, **kwargs):
        pts   = hv.Points(taxi, [self.location+'_x', self.location+'_y'])
        trips = datashade(pts, cmap=palette[self.cmap], **dopts)
        return tiles.options(alpha=self.alpha) * trips

explorer = NYCTaxi(name="Taxi explorer")
pn.Row(explorer, explorer.make_view).servable()
Out[20]:

Note that in this simple app, the method make_view is called whenever any of the parameters change (alpha, colormap, or location), but you can get a more responsive interface if you take the time to declare which computations depend on which parameters (see the Deploying Bokeh Apps tutorial ).

As you can see, the PyViz tools let you integrate visualization into everything you do, using a small amount of code that reveals your data's properties and captures your understanding of it. The rest of these tutorials will break down each of the topics covered above, showing you step by step how to work with your own data using these tools.

Thanks to all of the PyViz contributors!


Right click to download this notebook from GitHub.